/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.member;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import util.MyLog;

/**
 *
 * @author Ngoc Linh
 */
@WebServlet(name = "uploadFile", urlPatterns = {"/member/uploadFile.do"})
public class uploadFile extends HttpServlet {

    private static final String TMP_DIR_PATH = "C:\\temp1";
    private File tmpDir;
    
    private String destination;
    private String urlReturn;
    private File destinationDir;
        
    @Override
    public void init() throws ServletException {
        //Khỏi tạo upload:
        tmpDir = new File(TMP_DIR_PATH);

        //Nếu chưa tồn tại thì tạo mới:
        if (tmpDir.exists() == false) {
            tmpDir.mkdir();
        }       
        
        //Gán mặc định:
        destination = "/images/data/";
        urlReturn = "home.do";
    }
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/xml");
        PrintWriter out = response.getWriter();
                
        try {
            
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); 
        fileItemFactory.setRepository(tmpDir);
        
        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);    
        
        HttpSession session = request.getSession();
        List<String> listFile = new ArrayList<String>();
        
        try {
            
            if(session.getAttribute("urlReturn") != null){
                urlReturn = (String)session.getAttribute("urlReturn");
            }
            
            if(session.getAttribute("destination") != null){
                destination = (String)session.getAttribute("destination");
                String realPath = getServletContext().getRealPath(destination);
                destinationDir = new File(realPath);
            }
            
            // Parse the request                 
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();

            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();

                if (item.isFormField() == false) {
                    //Handle Uploaded files
                    //Write data to file  
                    String content = item.getContentType();
                    long size = item.getSize();
                                        
                    if (size /(1024*1024) < 1 && (content.contains("png") || content.contains("jpg") || content.contains("gif") || content.contains("jpeg"))) {
                        File file = new File(destinationDir, item.getName().toLowerCase().replace(' ', '_'));
                        item.write(file);
                        
                        if(listFile.contains(file.getName()) == false){
                            listFile.add(file.getName());
                        }                        
                    }                    
                }
            }
            
        } catch (FileUploadException ex) {
            MyLog.WriteLog(ex, "Lỗi phân tích yêu cầu upload file: " + ex.getMessage());
        } catch (Exception ex) {
            MyLog.WriteLog(ex, "Lỗi phân tích yêu cầu upload file: " + ex.getMessage());         
        }
        
        session.setAttribute("upload", listFile);
        response.sendRedirect(urlReturn);             
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Upload files";
    }// </editor-fold>
}
